<?php
/**
 * 汇友科技
 * @copyright (c) 2017 http://www.huiyou365.net All rights reserved.
 * @author: Creatint <creatint@163.com>
 */
namespace Common\Tool;

use ZipArchive;

class Zip{
    public static function zipDir( $sourcePath, $outZipPath){
        $pathInfo = pathInfo($sourcePath);
        $parentPath = $pathInfo['dirname'];
        $dirName = $pathInfo['basename'];
        $z = new ZipArchive();
        $z->open($outZipPath, ZIPARCHIVE::CREATE);
        $z->addEmptyDir($dirName);
        self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
        $z->close();
    }

    public static function folderToZip( $folder, &$zipFile, $exclusiveLength){
        $handle = opendir( $folder );
        while( false !== $f = readdir($handle) ) {
            if ( $f != '.' && $f != '..' ) {
                $filePath = "$folder/$f";
                $localPath = substr( $filePath, $exclusiveLength );
                if ( is_file($filePath) ) {
                    $zipFile->addFile($filePath, $localPath);
                } elseif ( is_dir($filePath) ) {
                    $zipFile->addEmptyDir($localPath);
                    self::folderToZip($filePath, $zipFile, $exclusiveLength);
                }
            }
        }
        closedir( $handle);
    }
}